let encoding = require('./encoding.js')
const util = {
    API: 'https://xinai.icu/api/',

    /**
     * 获取窗口大小
     */
    getWindowSize(that) {
        let pages = getCurrentPages(); // 当前页面
        // let beforePage = pages[pages.length - 2]; 
        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    model: res.model,
                    width: res.windowWidth,
                    height: res.windowHeight,
                    topHeight: res.statusBarHeight + 46,
                    pageLength: pages.length
                })
            },
        })
    },
    login(cb) {
        var that = this;
        wx.login({
            success(res) {
                that.post('wx/user/login', {
                    js_code: res.code
                }, function (res) {
                    if (res.code == -1) {
                        wx.showToast({
                            title: res.data.msg + '',
                            icon: 'none'
                        })
                    } else if (res.code == 1) {
                        wx.setStorageSync("user", res.data)
                        wx.setStorageSync("token", res.token)
                        cb(res)
                    }
                })
            }
        })
    },
    //post请求
    post(url, data, success, fail) {
        this.http('POST', url, data, success, fail)
    },
    get(url, data, success, fail) {
        this.http('GET', url, data, success, fail)
    },

    http(method, url, data, success, fail) {
        //通用post接口实现方法
        var that = this;
        let _data = data || {};
        let _success = success || function (e) {
            console.log(e)
        };
        let _fail = fail || function (e) {
            console.log(e)
        };
        let _method = method || 'POST';
        let _header = {
            'content-type': 'application/x-www-form-urlencoded'
        };

        if (_method.toUpperCase() == 'GET') {
            _header = {
                'content-type': 'application/json'
            };
        }
        if (wx.getStorageSync("token")) {
            _header.token = wx.getStorageSync("token")
        }
        if (arguments.length == 2 && typeof _data == 'function') {
            _success = _data
        }
        wx.request({
            url: this.API + url,
            method: _method,
            header: _header,
            data: _data,
            success: function (res) {
                if (typeof _success == 'function' && res.statusCode != 404 && res.statusCode != 500 && res.statusCode != 400) {
                    _success(res.data);
                    if (res.data.code == -1) {
                        that.login(function (res) {
                            that.http(method, url, data, success, fail)
                        })
                    } else if (res.data.code != 1) {
                        wx.showToast({
                            title: res.data.msg + '',
                            icon: 'none'
                        })
                    }
                } else {
                    if (typeof _success != 'function') {}
                    wx.showToast({
                        title: '接口错误 ' + res.statusCode,
                        icon: 'none'
                    })
                }
            },
            fail: function (res) {
                console.log(`======== 接口请求失败 ========`);
                if (typeof _fail == 'function') {
                    _fail(res);
                }
            }
        });
    },
    dateFormat(time, fmt) { //author: meizz 
        let date = new Date(parseInt(time))
        var o = {
            "M+": date.getMonth() + 1, //月份 
            "d+": date.getDate(), //日 
            "h+": date.getHours(), //小时 
            "m+": date.getMinutes(), //分 
            "s+": date.getSeconds(), //秒 
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    },

    navTo(e) {
        let type = e.currentTarget.dataset.type
        let names = e.currentTarget.dataset.names
        let path = e.currentTarget.dataset.path
        let nav = 'navigateTo'
        if (type == 1) {
            nav = 'navigateTo'
        } else if (type == 2) {
            nav = 'redirectTo'
        } else if (type == 3) {
            nav = 'switchTab'
        }
        let url = path
        let _names = []
        if (names) {
            _names = names.split(',')
        }
        if (_names.length > 0) {
            url += '?'
            for (let i in _names) {
                if (i == 0) {
                    url += _names[i] + '=' + e.currentTarget.dataset[_names[i]]
                } else {
                    url += '&' + _names[i] + '=' + e.currentTarget.dataset[_names[i]]
                }
            }
        }
        wx[nav]({
            url: url,
        })
    },
    wxpay(msg, cb) {
        wx.requestPayment({
            timeStamp: msg.timestamp,
            nonceStr: msg.nonceStr,
            package: msg.package,
            signType: 'MD5',
            paySign: msg.paySign,
            success(res) {
                wx.showToast({
                    title: '发布成功',
                })
                util.post('help/update/state', {
                    state: 1,
                    is_pay: 1,
                    id: msg.oid
                }, function (res) {
                    if (res.code == 1) {
                        if (cb) {
                            cb(true)
                        } else {
                            wx.redirectTo({
                                url: '/pages/order/detail/detail?id=' + msg.oid,
                            })
                        }

                    } else {
                        if (cb) {
                            cb(false)
                        } else {
                            wx.redirectTo({
                                url: '/pages/order/detail/detail?id=' + msg.oid,
                            })
                        }
                    }
                })
            },
            fail(res) {
                wx.showToast({
                    title: '支付失败',
                    icon: 'none'
                })
                if (cb) {
                    cb(false)
                } else {
                    wx.redirectTo({
                        url: '/pages/order/detail/detail?id=' + msg.oid,
                    })
                }
            }
        })
    },
    formatMsgTime(timespan) {
        var dateTime = new Date(timespan);
        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var day = dateTime.getDate();
        var hour = dateTime.getHours();
        var minute = dateTime.getMinutes();
        var second = dateTime.getSeconds();
        var now = new Date();
        var now_new = now.getTime(); //typescript转换写法

        var milliseconds = 0;
        var timeSpanStr;

        milliseconds = now_new - dateTime.getTime();

        if (milliseconds <= 1000 * 60 * 1) {
            timeSpanStr = '刚刚';
        } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
            timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
        } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
            timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
        } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
            timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
        } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
            timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute;
        } else {
            timeSpanStr = timespan;
        }
        return timeSpanStr;
    },

    cancel(oid, name, cb) {
        this.post('help/update/state', {
            state: 4,
            id: oid
        }, function (res) {

            if (res.code == 1) {
                wx.showToast({
                    title: '取消成功',
                })
                cb(true)
            } else {
                cb(false)
                wx.showToast({
                    title: '取消失败',
                    icon: 'none'
                })
            }
        })
    }, //

    // 拿到需要返回的页面路径和参数并保存 （跳转之前调用此方法）
    setCallbackUrl: function (mode) {
        return new Promise((resolve, reject) => {
            let pages = getCurrentPages(); //获取历史页面记录
            let currentPage = pages[pages.length - 1]; //获取当前页面
            let urlPage = '';
            let url = currentPage.route; //拿到当前页面url
            let argumentsStr = '';
            let options = currentPage.options; //拿到参数对象
            for (let key in options) {
                let value = options[key];
                argumentsStr += key + '=' + value + '&';
            }
            if (argumentsStr) {
                argumentsStr = argumentsStr.substring(0, argumentsStr.length - 1);
                urlPage = url + '?' + argumentsStr;
            } else {
                urlPage = url;
            }
            console.log("currentPage: " + urlPage);
            let callbackObj = {
                callbackUrl: `/${urlPage}`,
                mode: mode || 'redirectTo'
            }
            wx.setStorageSync('callbackObj', JSON.stringify(callbackObj));
            resolve();
        })
    },

    // 提取本地存储的要返回的页面地址和参数，并返回之前的页面（登录完成后调用此方法）
    getCallBackUrl: function () {
        return new Promise((resolve, reject) => {
            const callbackObj = wx.getStorageSync('callbackObj');
            if (callbackObj) {
                let resultObj = JSON.parse(callbackObj);
                let callbackUrl = resultObj.callbackUrl;
                let mode = resultObj.mode;
                mode == 'redirectTo' && wx.redirectTo({
                    url: callbackUrl
                });
                mode == 'switchTab' && wx.switchTab({
                    url: callbackUrl
                });
                mode == 'reLaunch' && wx.reLaunch({
                    url: callbackUrl
                });
                if (mode == 'navigateTo') {
                    console.log("跳转到当前页面：" + callbackUrl)
                    wx.navigateTo({
                        url: callbackUrl
                    });
                }
            } else {
                reject();
            }
        })
    },

    toast: function (title) {
        wx.showToast({
            title: title,
            icon: 'none',
            duration: 1500,
            success() {
                setTimeout(() => {
                    wx.hideToast();
                }, 2000);

            }
        });
    },

    loading: function (title) {
        wx.showLoading({
            title: title,
            mask: true,
        });
    },

    hide_Loading: function () {
        wx.hideLoading();
    },

    // ArrayBuffer转16进度字符串示例
    ab2hex: function (buffer) {
        let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2);
            }
        );
        return hexArr.join('');
    },


    /**
     * 16进制字符串转ArrayBuffer
     */
    hex2ab: function (str) {
        if (!str) {
            return new ArrayBuffer(0);
        }
        let typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
            return parseInt(h, 16)
        }));
        let buffer1 = typedArray.buffer;
        console.log("hex2ab = ", buffer1);
        return buffer1;
    },
    // 微信字符串转ArrayBuffer
    stringToArrayBuffer: function (str) {
        var bytes = new Array();
        var len, c;
        len = str.length;
        for (var i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if (c >= 0x010000 && c <= 0x10ffff) {
                bytes.push(((c >> 18) & 0x07) | 0xf0);
                bytes.push(((c >> 12) & 0x3f) | 0x80);
                bytes.push(((c >> 6) & 0x3f) | 0x80);
                bytes.push((c & 0x3f) | 0x80);
            } else if (c >= 0x000800 && c <= 0x00ffff) {
                bytes.push(((c >> 12) & 0x0f) | 0xe0);
                bytes.push(((c >> 6) & 0x3f) | 0x80);
                bytes.push((c & 0x3f) | 0x80);
            } else if (c >= 0x000080 && c <= 0x0007ff) {
                bytes.push(((c >> 6) & 0x1f) | 0xc0);
                bytes.push((c & 0x3f) | 0x80);
            } else {
                bytes.push(c & 0xff);
            }
        }
        var array = new Int8Array(bytes.length);
        for (var i in bytes) {
            array[i] = bytes[i];
        }
        return array.buffer;
    },

    /**
     * 十六进制字符串转中文
     * @param {String} hex 为十六进制字符串
     * @return {String} 包含中文的字符串
     */
    hexToStr: function (hex) {
        // 去掉字符串首尾空格
        let trimedStr = hex.trim()
        // 判断trimedStr前两个字符是否为0x，如果是则截取从第三个字符及后面所有，否则返回全部字符
        let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr
        // 得到rawStr的长度
        let len = rawStr.length
        // 如果长度不能被2整除，那么传入的十六进制值有误，返回空字符
        if (len % 2 !== 0) {
            return ""
        }
        let curCharCode // 接收每次循环得到的字符
        let resultStr = [] // 存转换后的十进制值数组
        for (let i = 0; i < len; i = i + 2) {
            curCharCode = parseInt(rawStr.substr(i, 2), 16)
            resultStr.push(curCharCode)
        }
        // encoding为空时默认为utf-8
        let bytesView = new Uint8Array(resultStr) // 8 位无符号整数值的类型化数组
        // TextEncoder和TextDecoder对字符串和字节流互转  
        // let str = new TextDecoder(encoding).decode(bytesView)因为小程序中没有TextDecoder,经查阅资料，下载https://github.com/inexorabletash/text-encoding并const encoding = require("./text-encoding-master/lib/encoding.js")引入后使用下面方式即可：
        let str = new encoding.TextDecoder("utf-8").decode(bytesView)
        return str
    },

    // 16进制字符串取需要的字节(fe 08 01 00 01 01 01 7a0b 008f)
    hexSlice: function (hex) {
        // 取k8位
        let k8 = hex.slice(14, 16);
        //取k9位
        let k9 = hex.slice(16, 18);
        return parseInt(k9 + k8, 16);
    },

    // 蓝牙写数据
    writeToBluetoothValue: function (deviceId, services_UUID, characteristic_UUID, buffer) {
        console.log("写入数据：", buffer)
        let value = this.stringToArrayBuffer(buffer);
        wx.writeBLECharacteristicValue({
            deviceId: deviceId,
            serviceId: services_UUID,
            characteristicId: characteristic_UUID,
            value: value,
            success(res) {
                console.log('向低功耗蓝牙设备特征值中写入二进制数据: 成功---');
                console.log(res);
            },
            fail(res) {
                console.log('向低功耗蓝牙设备特征值中写入二进制数据: 失败---');
                console.log(res);
            }
        })
    },

    //修改mtu值
    exchange_mtu: function(deviceId) {
        wx.setBLEMTU({
            deviceId: deviceId,
            mtu: 512,
            success(res) {
                console.log("设置mtu成功: ", res)
            },
            fail(res) {
                console.log("设置mtu失败: ", res)
            },
        });
    },

}
module.exports = util